#include	"Socket.hh"

bool		Socket::createSocket(void)
{
  if ((this->fd = socket(AF_INET, SOCK_STREAM, 0)) > 0)
    return true;
  return false;
}

bool		Socket::connectSocket(std::string addr, int port)
{
  struct in_addr*	addr_ptr;
  struct hostent*	host_ptr;
  struct sockaddr_in	sockaddr;
  std::string		tmp;

  host_ptr = gethostbyname(addr.c_str());
  if (host_ptr == NULL)
    return false;
  addr_ptr = (struct in_addr*)*host_ptr->h_addr_list;
  tmp = inet_ntoa(*addr_ptr);
  if (tmp == "")
    return false;
  sockaddr.sin_family = AF_INET;
  sockaddr.sin_port = htons(port);
  sockaddr.sin_addr.s_addr = inet_addr(tmp.c_str());
  if (connect(this->fd, (struct sockaddr *)&sockaddr, sizeof(struct sockaddr)) == 0)
    return true;
  return false;
}

bool		Socket::closeSocket(void)
{
  if (this->fd)
    {
      if (!close(this->fd))
	return true;
      return false;
    }
  return false;
}

ssize_t		Socket::readSocket(char *msg, size_t len)
{
  return recv(this->fd, msg, len, 0);
}

ssize_t		Socket::writeSocket(const char *msg, size_t len)
{
  return send(this->fd, msg, len, 0);
}
